<template>
  <div class="map-content"></div>
</template>

<script setup>
  import { ref, onMounted, inject } from "vue";

  const bus = inject("bus");
  const myMap = ref();

  onMounted(() => {
    bus.on("map", ({ map, AMap }) => {
      myMap.value = map;

      // myMap.value.on("zoomend", function (e) {
      //   console.log(this.getZoom());
      // });

      myMap.value.setCenter([116.397428, 39.90923]);
      myMap.value.setZoom(10);
      let marker = new AMap.Marker({
        position: new AMap.LngLat(116.397457, 39.909188),
      });
      marker.on("click", function () {
        // marker.setMap(null);// 移除标记
        // myMap.value.remove(marker);
        // 添加弹窗
        var infoWindow = new AMap.InfoWindow({
          content: `<div class="custom-info-window">
            <h3>自定义标题</h3>
            <p>这是自定义内容。</p>
          </div>`,
        });
        infoWindow.open(myMap.value, marker.getPosition());
        myMap.value.setFitView(null, true);
      });
      myMap.value.add(marker);
      myMap.value.setFitView(); // 根据地图上添加的覆盖物分布情况，自动缩放地图到合适的视野级别

      myMap.value.on("click", function (e) {
        console.log(e);

        // 点击添加的标记
        var marker = new AMap.Marker({
          position: new AMap.LngLat(e.lnglat.getLng(), e.lnglat.getLat()),
        });
        marker.on("click", function () {
          marker.setMap(null); // 移除标记
          myMap.value.remove(marker);
        });
        myMap.value.add(marker);
        myMap.value.setFitView();
      });
    });
  });
</script>
<style lang="scss" scoped>
  .map-content {
    position: relative;
    width: 100%;
    height: 100%;
    pointer-events: none;
  }

  :deep(.custom-info-window) {
    background-color: white;
    border-radius: 10px;
    box-shadow: 0px 2px 6px rgba(0, 0, 0, 0.2);
    padding: 10px;
    font-size: 14px;
  }

  :deep(.custom-info-window) h3 {
    margin: 0;
    font-size: 16px;
    color: #333;
  }

  :deep(.custom-info-window) p {
    margin: 5px 0 0;
    color: #666;
  }
</style>
